package com.study.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.app.domain.AppSystemNotifications;
import com.study.app.domain.AppUser;
import com.study.app.domain.AppUserFeedback;
import com.study.app.domain.bo.AppUserFeedbackBo;
import com.study.app.domain.vo.AppUserFeedbackVo;
import com.study.app.mapper.AppSystemNotificationsMapper;
import com.study.app.mapper.AppUserFeedbackMapper;
import com.study.app.mapper.AppUserMapper;
import com.study.app.service.IAppUserFeedbackService;
import com.study.common.core.domain.PageQuery;
import com.study.common.core.page.TableDataInfo;
import com.study.common.utils.AesGcmUtils;
import com.study.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户问题反馈Service业务层处理
 *
 * @author study
 * @date 2023-04-20
 */
@RequiredArgsConstructor
@Service
public class AppUserFeedbackServiceImpl implements IAppUserFeedbackService {

    private final AppUserFeedbackMapper baseMapper;
    private final AppUserMapper appUserMapper;
    private final AppSystemNotificationsMapper appSystemNotificationsMapper;

    /**
     * 查询用户问题反馈
     */
    @Override
    public AppUserFeedbackVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户问题反馈列表
     */
    @SneakyThrows
    @Override
    public TableDataInfo<AppUserFeedbackVo> queryPageList(AppUserFeedbackBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppUserFeedback> lqw = buildQueryWrapper(bo);
        Page<AppUserFeedbackVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (AppUserFeedbackVo record : result.getRecords()) {
            record.setUserPhone(AesGcmUtils.decrypt(record.getUserPhone()));
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户问题反馈列表
     */
    @Override
    public List<AppUserFeedbackVo> queryList(AppUserFeedbackBo bo) {
        LambdaQueryWrapper<AppUserFeedback> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppUserFeedback> buildQueryWrapper(AppUserFeedbackBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppUserFeedback> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getUserCode()), AppUserFeedback::getUserCode, bo.getUserCode());
        lqw.eq(StringUtils.isNotBlank(bo.getUserPhone()), AppUserFeedback::getUserPhone, bo.getUserPhone());
        lqw.eq(bo.getCategory() != null, AppUserFeedback::getCategory, bo.getCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), AppUserFeedback::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getContentReply()), AppUserFeedback::getContentReply, bo.getContentReply());
        lqw.eq(StringUtils.isNotBlank(bo.getImages()), AppUserFeedback::getImages, bo.getImages());
        lqw.eq(bo.getStatus() != null, AppUserFeedback::getStatus, bo.getStatus());
        lqw.orderByDesc(AppUserFeedback::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户问题反馈
     */
    @Override
    public Boolean insertByBo(AppUserFeedbackBo bo) {
        AppUserFeedback add = BeanUtil.toBean(bo, AppUserFeedback.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户问题反馈
     */
    @Override
    public Boolean updateByBo(AppUserFeedbackBo bo) {
        AppUserFeedback update = BeanUtil.toBean(bo, AppUserFeedback.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppUserFeedback entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户问题反馈
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<AppUserFeedbackVo> getUserQuery(String userCode) {
        return baseMapper.selectVoList(new LambdaQueryWrapper<AppUserFeedback>().eq(AppUserFeedback::getUserCode, userCode)
                .orderByDesc(AppUserFeedback::getCreateTime));
    }

    @Override
    @Transactional
    public Boolean changePro(Long id,String contentReply) {
        AppUserFeedbackVo appUserFeedbackVo = baseMapper.selectVoById(id);
        //查找到反馈用户的详细信息
        AppUser appUser = appUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery()
                .eq(StringUtils.isNotBlank(appUserFeedbackVo.getUserCode()), AppUser::getUserCode, appUserFeedbackVo.getUserCode()));

        AppSystemNotifications appSystemNotifications = new AppSystemNotifications();
        appSystemNotifications.setRecipientId(appUser.getId());
        appSystemNotifications.setIsType(AppSystemNotifications.TIP);
        appSystemNotifications.setNotificationContent("您有一条反馈问题已回复，请到“反馈记录”查看。");
        appSystemNotifications.setNotificationTitle("反馈记录");
        appSystemNotifications.setSendTime(LocalDateTime.now());
        appSystemNotificationsMapper.insert(appSystemNotifications);


        return baseMapper.update(null, new LambdaUpdateWrapper<AppUserFeedback>().eq(AppUserFeedback::getId, id)
                .set(AppUserFeedback::getStatus, 2)
                .set(AppUserFeedback::getContentReply,contentReply)) > 0;
    }
}
